package UnionFind;

public class QuickUnionUF {
    private int[] id;
    private int count;

    public QuickUnionUF(int N) {
        id = new int[N];
        for (int i = 0; i <N; i++) {
            id[i] = i;
            count++;
        }
    }

    public int count() {
        return count;
    }

    public boolean connected(int p, int q) {
        return find(p)==find(q);
    }
    public int find(int q) {
        while (q != id[q]) {
            q = id[q];
        }
        return q;
    }

    public void union(int p, int q) {
        if (find(p) == find(q)) {
            return;
        }
        id[find(q)] = find(p);
        count--;
    }

}
